//
//  QianBaoTiViewController.m
//  DBAChain
//
//  Created by Evan on 2018/9/9.
//  Copyright © 2018 Evan. All rights reserved.
//

#import "QianBaoTiViewController.h"
#import "QRCodeScanViewController.h"
#import "mentionViewController.h"
#import "taskOverviewService.h"
#import "taskUserManagerService.h"
#import "HomePassWordView.h"
#import <Masonry.h>
#import "dataTransferInfo.h"
#import "MeModifyViewController.h"
#import "viewPayValidate.h"
#import "MeAuthenticationViewController.h"
#import "MeSecurityViewController.h"

@interface QianBaoTiViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *layoutToView;
@property (weak, nonatomic) IBOutlet UITextField *recChainField;
@property (weak, nonatomic) IBOutlet UITextField *transferCountField;
@property (weak, nonatomic) IBOutlet UILabel *lbamout;
@property (weak, nonatomic) IBOutlet UILabel *lbfee;
@property (weak, nonatomic) IBOutlet UILabel *lbdestCount;
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UILabel *lbtitle;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (nonatomic,strong)HomePassWordView *viewPassword;
@property (nonatomic,strong)viewPayValidate  *viewPayValid;
@property (nonatomic,strong)dataTransferDInfo *tranModel;
@property (nonatomic,strong)dataUserValidateInfo    *modelUserValidate;
@property (nonatomic,strong)NSString *gteCode;
//@ApiModelProperty("货币类型 0:GTe,1:GTK")
//private Integer currencyType;
//@ApiModelProperty("提币地址")
//private String recChain;
//@ApiModelProperty("提币数量")
//private String transferCount;
//@ApiModelProperty("手续费数量")
//private String fee;
//@ApiModelProperty("到账数量")
//private String destCount;
//@ApiModelProperty("支付密码")
//private String payPassword;
@end

@implementation QianBaoTiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title =self.isGTE ? @"GTE提币" : @"GTK提币";
    self.modelUserValidate = [dataUserValidateInfo new];
    [self initUI];
    [self loadData];
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapSliderAction)]];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadPayValidate];
    [self setBlackStatus:YES];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:LCFromRGB(51, 51, 51), NSForegroundColorAttributeName, nil]];
    if (self.navigationController.navigationBar.hidden == YES) {
        self.navigationController.navigationBar.hidden = NO;
    }
}

-(void)initUI{
    if (@available(iOS 11.0, *)) {
        self.layoutToView.constant = 0;
    } else {
        self.layoutToView.constant = 64;
    }
    self.textView.hidden = !self.isGTE;
    self.codeButton.hidden = !self.isGTE;
    self.lbdestCount.text = [NSString stringWithFormat:@"0.00000000 %@",[self returnGteIsGtk]];
    self.lbtitle.text = self.isGTE ? @"提币地址" :@"对方GTK编码";
}

-(viewPayValidate*)viewPayValid{
    if (!_viewPayValid ){
        _viewPayValid = [[[NSBundle mainBundle] loadNibNamed:@"viewPayValidate" owner:nil options:nil] objectAtIndex:0];
        [_viewPayValid initUI];
        [self.view addSubview:_viewPayValid];
        _viewPayValid.hidden = YES;
        [_viewPayValid mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(self.view);
            make.top.offset(60);
            make.bottom.mas_equalTo(self.view).offset(0);
        }];
        [_viewPayValid.btnSubmit addTarget:self action:@selector(btnSubmitClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _viewPayValid.labelNo3.hidden = YES;
        _viewPayValid.imgNo3.hidden = YES;
    }
    return _viewPayValid;
}

///用户验证点击完成
-(void)btnSubmitClick:(UIButton*)sender{
    if (!self.modelUserValidate.payPasswordVerify) {
        //跳转到设置支付密码页面
        [self.navigationController pushViewController:[[MeModifyViewController alloc]initWithType:1] animated:YES];
    }else if(!self.modelUserValidate.infoVerify){
        //跳转到实名认证页面
        [self.navigationController pushViewController:[MeAuthenticationViewController new] animated:YES];
    }
//    else if(!self.modelUserValidate.safeVerify){
//        //跳转到安全认证页面
//        [self.navigationController pushViewController:[MeSecurityViewController new] animated:YES];
//    }
}

#pragma mark - loadData
-(void)loadData{
    [self loadTiBiInit];
    if (self.isGTE) {
        [taskOverviewService getRecharge:nil success:^(dataCodeInfo *response, BOOL success) {
            if (success) {
                self.gteCode = response.data;
            }
        } failture:^(NSError *error, NSString *strDescription) {
            
        }];
    }else{
        self.gteCode = [UserCenter shareCenter].user.userNo;
    }
}

///获取登录用户的账户验证信息资料
-(void)loadPayValidate{
    [taskUserManagerService getUserValidateInfo:nil success:^(dataUserValidateInfo *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            
            self.modelUserValidate =  [dataUserValidateInfo mj_objectWithKeyValues:response];
            [self isValidateSuccess];
        }else{
            [DKProgressHUD showErrorWithStatus:response.statusDesc];
        }
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

///获取提币基础配置信息
- (void)loadTiBiInit{
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setField:self.isGTE ? @"0" : @"1" value:@"currencyType"];
    [DKProgressHUD showLoading];
    [taskOverviewService getopenTransfer:dict success:^(dataTransferInfo *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            self.tranModel = response.data;
            self.lbamout.text =[NSString stringWithFormat:@"%@%@",self.tranModel.amount,[self returnGteIsGtk]];
        }else{
            [DKProgressHUD showErrorWithStatus:response.statusDesc];
        }
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

-(BOOL) isValidateSuccess{
    self.viewPayValid.hidden = YES;
    if (!self.modelUserValidate.infoVerify || !self.modelUserValidate.payPasswordVerify) {
        self.viewPayValid.hidden = NO;
        
        //隐藏安全验证信息
        self.viewPayValid.labelNo3.hidden = YES;
        self.viewPayValid.imgNo3.hidden = YES;
        
        UIColor *colorF = LCFromRGB(240, 92, 164);
        UIColor *colorF_no = LCFromRGB(102, 102, 102);
        UIImage *imgleftCheck = [UIImage imageNamed:@"leftCheck"];
        UIImage *imgleftCheck_no = [UIImage imageNamed:@"leftCheck_no"];
        
        self.viewPayValid.labelNo1.textColor = colorF_no;
        self.viewPayValid.imgNo1.image = imgleftCheck_no;
        self.viewPayValid.labelNo2.textColor = colorF_no;
        self.viewPayValid.imgNo2.image = imgleftCheck_no;
//        self.viewPayValid.labelNo3.textColor = colorF_no;
//        self.viewPayValid.imgNo3.image = imgleftCheck_no;
        
        if (self.modelUserValidate.payPasswordVerify == 1) {
            self.viewPayValid.labelNo1.textColor = colorF;
            self.viewPayValid.imgNo1.image = imgleftCheck;
            
        }
        if (self.modelUserValidate.infoVerify == 1) {
            self.viewPayValid.labelNo2.textColor = colorF;
            self.viewPayValid.imgNo2.image = imgleftCheck;
        }
//        if (self.modelUserValidate.safeVerify == 1) {
//            self.viewPayValid.labelNo3.textColor = colorF;
//            self.viewPayValid.imgNo3.image = imgleftCheck;
//        }
        
        NSString *str = @"设置支付密码";
        if (!(self.modelUserValidate.payPasswordVerify == 1)) {
            str = @"设置支付密码";
        }else if(!(self.modelUserValidate.infoVerify == 1)){
            str = @"实名认证";
        }
//        else if(!(self.modelUserValidate.safeVerify == 1)){
//            str = @"安全认证";
//        }
        [self.viewPayValid.btnSubmit setTitle:str forState:UIControlStateNormal];
        
        return NO;
    }
    return YES;
}


#pragma mark - init
-(HomePassWordView*)viewPassword{
    if (!_viewPassword ){
        _viewPassword = [[[NSBundle mainBundle] loadNibNamed:@"HomePassWordView" owner:nil options:nil] objectAtIndex:0];
        [_viewPassword initUI];
        [self.view addSubview:_viewPassword];
        _viewPassword.hidden = YES;
        [_viewPassword mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.and.right.mas_equalTo(self.view);
            make.top.offset(60);
            make.bottom.mas_equalTo(self.view).offset(0);
        }];
        [_viewPassword.btnNext setTitle:@"确认提币" forState:UIControlStateNormal];
    }
    return _viewPassword;
}

- (IBAction)gteAction:(id)sender {
    
    if (![self isValidateSuccess]) {
        return;
    }
    
    if (![Check checkLenght:self.recChainField.text]) {
        [DKProgressHUD showErrorWithStatus:@"请输提币地址"];
        return;
    }
    if ([self.recChainField.text isEqualToString:self.gteCode]) {
        [DKProgressHUD showErrorWithStatus:@"不能输入自己的提币地址"];
        return;
    }
    if (![Check IsABChinese:self.transferCountField.text]) {
        [DKProgressHUD showErrorWithStatus:@"请输有效的提币数量"];
        return;
    }
    if (!([self.transferCountField.text floatValue] >= 20)) {
        [DKProgressHUD showErrorWithStatus:@"需至少提现20GTE"];
        return;
    }
    
    if ([self.transferCountField.text floatValue] > [self.tranModel.amount floatValue]) {
        [DKProgressHUD showErrorWithStatus:@"GTE不足，请充值"];
        return;
    }
        ///进入输入密码的模块
        self.viewPassword.hidden = NO;
        __block QianBaoTiViewController *  blockSelf = self;
        self.viewPassword.blockSubmit = ^(NSString *pwd) {
            [blockSelf getTransferload:pwd];
        };
}

-(void)getTransferload:(NSString *)payPassword{
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setField:self.isGTE ? @"0" : @"1" value:@"currencyType"]; //0gte 1gtk
//    if (self.isGTE) {
    [dict setField:self.recChainField.text value:@"recChain"];
//    }else{
//        [dict setField:self.recChainField.text value:@"gtkAccount"];
//    }
    [dict setField:self.transferCountField.text value:@"transferCount"];
    [dict setField:self.tranModel.fee value:@"fee"];
    [dict setField:[NSString stringWithFormat:@"%lf",([self.transferCountField.text floatValue] - [self.tranModel.fee floatValue])] value:@"destCount"];
    [dict setField:payPassword value:@"payPassword"];
    [DKProgressHUD showLoading];
    [taskOverviewService getTransfer:dict success:^(BaseModel *response, BOOL success) {
        [DKProgressHUD dismiss];
        if (success) {
            [DKProgressHUD showErrorWithStatus:@"提币成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [DKProgressHUD showErrorWithStatus:response.statusDesc];
        }
    } failture:^(NSError *error, NSString *strDescription) {
        [DKProgressHUD dismiss];
        [DKProgressHUD showErrorWithStatus:strDescription];
    }];
}

- (IBAction)codeAction:(id)sender {
    QRCodeScanViewController *vc = [QRCodeScanViewController new];
    __weak __typeof(self)weakSelf = self;
    vc.blockQR = ^(NSString *strQR) {
        weakSelf.recChainField.text = strQR;
    };
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.view endEditing:YES];
    if ([Check IsABChinese:self.transferCountField.text]) {
        self.lbfee.text =[NSString stringWithFormat:@"%.2f%@",[self.transferCountField.text floatValue]*[self.tranModel.fee floatValue],[self returnGteIsGtk]];
        self.lbdestCount.text = [NSString stringWithFormat:@"%.2f%@",[self.transferCountField.text floatValue] - [self.transferCountField.text floatValue]*[self.tranModel.fee floatValue],[self returnGteIsGtk]];
    }
}

-(NSString *)returnGteIsGtk{
    return self.isGTE ? @"GTE" : @"GTK";
}

-(void)tapSliderAction
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)btnAll:(id)sender {
     self.transferCountField.text = self.tranModel.amount;
}



@end
